package com.example.bookmall.service.impl;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bookmall.entity.Book;
import com.example.bookmall.entity.Category;
import com.example.bookmall.entity.Result;
import com.example.bookmall.mapper.BookMapper;
import com.example.bookmall.mapper.CategoryMapper;
import com.example.bookmall.service.BookService;
import com.example.bookmall.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;


@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BookMapper bookMapper;


    //管理员端添加图书
    @Override
    public Result addBook(Book book){
        // 1. 先检查ISBN是否已存在
        Book existingBook = bookMapper.selectOne(
                new LambdaQueryWrapper<Book>().eq(Book::getIsbn, book.getIsbn()));

        if (existingBook != null) {
            return Result.error("ISBN已存在，添加失败");
        }
        book.setCreateTime(LocalDateTime.now());

        int result = bookMapper.insert(book);

        return result > 0 ?
                Result.success("添加图书成功") :
                Result.error("添加图书失败，数据库操作异常");
    }

    //管理员端上架图书
    @Override
    @Transactional
    public boolean publishBook(Integer bookId) {
        return lambdaUpdate()
                .eq(Book::getBookId, bookId)
                .set(Book::getStatus, 1) // 1=上架
                .update();
    }
    //管理员端下架图书
    @Override
    @Transactional
    public boolean unpublishBook(Integer id) {
        return lambdaUpdate()
                .eq(Book::getBookId, id)
                .set(Book::getStatus, 0) // 0=下架
                .update();
    }
    //管理员端修改图书信息
    @Override
    public Result modifyBook(Integer bookId, Book book) {
        if (bookId == null || book == null) {
            return Result.error("图书信息不能为空");
        }

        // 获取数据库中现有的图书
        Book existingBook = bookMapper.selectById(bookId);
        if (existingBook == null) {
            return Result.error("图书不存在");
        }

        // 检查ISBN是否修改
        boolean isbnChanged = !Objects.equals(book.getIsbn(), existingBook.getIsbn());

        if (isbnChanged) {
            // 如果ISBN有修改，检查新ISBN是否已存在
            boolean isbnExists = bookMapper.exists(new LambdaQueryWrapper<Book>()
                    .eq(Book::getIsbn, book.getIsbn())
                    .ne(Book::getBookId, bookId)); // 排除当前图书
            if (isbnExists) {
                return Result.error("ISBN已存在，不允许修改");
            }
        }
        // 执行更新操作
        boolean success = lambdaUpdate()
                .eq(Book::getBookId, bookId)
                .set(Book::getTitle, book.getTitle())
                .set(Book::getAuthor, book.getAuthor())
                .set(Book::getPublisher, book.getPublisher())
                .set(Book::getPrice, book.getPrice())
                .set(Book::getStock, book.getStock())
                .set(Book::getIsRecommended, book.getIsRecommended())
                .set(Book::getIsBanner, book.getIsBanner())
                .set(Book::getCategoryId, book.getCategoryId())
                .set(Book::getDescription, book.getDescription())
                .set(Book::getCoverUrl, book.getCoverUrl())
                .set(Book::getUpdateTime,LocalDateTime.now())
                .set(isbnChanged, Book::getIsbn, book.getIsbn())
                .update();

        return success
                ? Result.success("图书修改成功")
                : Result.error("图书修改失败");
    }

    //管理员端删除图书
    @Override
    public boolean deleteBook(Integer bookId) {

        Book book = bookMapper.selectById(bookId);

        book.setDeleted(1);
        book.setUpdateTime(LocalDateTime.now());
        bookMapper.updateById(book);

        int rows = bookMapper.updateById(book);
        return rows > 0;
    }

    //获取所有图书 默认查询所有 管理员端使用
    @Override
    public IPage<Book> listBooks(Integer page, Integer pageSize) {
        // 创建分页对象
        Page<Book> pageParam = new Page<>(page, pageSize);

        // 创建查询条件（查询所有上架图书）
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("deleted", 0);
       /* queryWrapper.eq("status", 1); // 1表示上架状态*/

        // 按更新时间降序排列
        queryWrapper.orderByDesc("update_time");

        // 执行分页查询
        return page(pageParam, queryWrapper);
    }

    //用户搜索图书 只能查询上架的图书
    @Override
    public Page<Book> searchBooks(String keyword, Integer pageNum, Integer pageSize) {
        // 构建分页对象
        Page<Book> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<Book>()
                .eq(Book::getStatus, 1)
                .eq(Book::getDeleted,0); // 始终过滤状态为1的图书

        // 如果关键词不为空，添加关键词相关的查询条件
        if (!StringUtils.isBlank(keyword)) {
            // 处理分类查询
            List<Category> categories = categoryMapper.selectList(
                    new LambdaQueryWrapper<Category>()
                            .like(Category::getCategoryName, keyword)
            );

            System.out.println("categories: " + categories);

            List<Integer> categoryIds = categories.stream()
                    .map(Category::getCategoryId)
                    .collect(Collectors.toList());

            // 构建多条件查询：书名、ISBN、作者、出版社、分类
            queryWrapper.and(wrapper -> {
                wrapper.like(Book::getTitle, keyword)
                        .or().like(Book::getIsbn, keyword)
                        .or().like(Book::getAuthor, keyword)
                        .or().like(Book::getPublisher, keyword)
                        .or().in(!categoryIds.isEmpty(), Book::getCategoryId, categoryIds);
            });
        }

        // 执行分页查询
        return bookMapper.selectPage(page, queryWrapper);
    }


    //用户获取图书列表 按分类
    @Override
    public List<Book> getBooksByCategory(Integer categoryId) {
        return lambdaQuery()
                .eq(Book::getCategoryId, categoryId)
                .eq(Book::getStatus, 1) // 只查询上架的图书
                .list();
    }

    //用户获取图书详情
    @Override
    public Book getBookDetails(Integer bookId) {
        return getById(bookId);
    }

    @Override
    public boolean existsById(Integer bookId) {
        if (bookId == null) {
            return false;
        }
        return bookMapper.exists(
                new LambdaQueryWrapper<Book>().eq(Book::getBookId, bookId)
        );
    }

    //获取图书
    @Override
    public Book getById(Integer bookId) {
        return bookMapper.selectById(bookId);
    }

    //用户搜索图书 根据标题
    @Override
    public Page<Book> searchByTitle(String title, int page, int pageSize) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        if (title != null && !title.isEmpty()) {
            queryWrapper.like("title", title);
        }
        return page(new Page<>(page, pageSize), queryWrapper);
    }

    //用户搜索图书 根据作者
    @Override
    public Page<Book> searchByAuthor(String author, Integer page, Integer pageSize) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        if (author != null && !author.isEmpty()) {
            queryWrapper.like("author", author);
        }
        return page(new Page<>(page, pageSize), queryWrapper);
    }

    //用户搜索图书 根据ISBN
    @Override
    public Page<Book> searchByIsbn(String isbn, Integer page, Integer pageSize) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        if (isbn != null && !isbn.isEmpty()) {
            queryWrapper.like("isbn", isbn);
        }
        return page(new Page<>(page, pageSize), queryWrapper);
    }


    //取消订单 加回库存
    @Override
    public void increaseStock(Integer bookId, Integer quantity) {
        // 1. 获取图书
        Book book = bookMapper.selectById(bookId);
        // 2. 增加库存
        book.setStock(book.getStock() + quantity);
        // 3. 更新数据库
        bookMapper.updateById(book);

    }

    //获取最新图书
    @Override
    public List<Book> getNewBooks(Integer count) {

        return bookMapper.selectList(
                new LambdaQueryWrapper<Book>()
                        .eq(Book::getDeleted, 0)
                        .eq(Book::getStatus, 1)  // 确保只查询上架图书
                        .orderByDesc(Book::getCreateTime)
                        .last("LIMIT " + count)
        );
    }
    //获取推荐图书
    @Override
    public List<Book> getRecommendBooks(Integer count) {
        return bookMapper.selectList(
                new QueryWrapper<Book>()
                        .eq("status", 1)                // 上架状态
                        .eq("is_recommended", 2)
                        .eq("deleted",0)
                        // 推荐状态
                        .orderByDesc("create_time")     // 按创建时间排序（新书优先）
                        .last("LIMIT " + count)
        );
    }

    //获取轮播图书
    @Override
    public List<Book> getBannerdBooks(Integer count) {
        return bookMapper.selectList(
                new QueryWrapper<Book>()
                        .eq("status", 1)                // 上架状态
                        .eq("is_banner", 2)
                        .eq("deleted",0)
                        // 轮播状态
                        .orderByDesc("create_time")     // 按创建时间排序（新书优先）
                        .last("LIMIT " + count)
        );
    }

    @Override
    public void decreaseStock(Integer bookId, Integer quantity) {
        // 1. 获取图书
        Book book = bookMapper.selectById(bookId);
        // 2. 增加库存
        book.setStock(book.getStock()- quantity);
        // 3. 更新数据库
        bookMapper.updateById(book);
    }


}